package com.itzyf.pokemondata.activity.panel

import android.content.Intent
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.avos.avoscloud.AVObject
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.GuildSettingActivity
import com.itzyf.pokemondata.bean.DbPokemon
import com.itzyf.pokemondata.utils.OnRefreshListener
import com.itzyf.pokemondata.utils.setOnRefreshListener
import com.itzyf.pokemondata.utils.subZeroAndDot
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_list_filter.*
import kotlinx.android.synthetic.main.activity_list_filter.ivStar
import kotlinx.android.synthetic.main.activity_list_filter.mBtnSearch
import kotlinx.android.synthetic.main.activity_list_filter.mSearchView
import kotlinx.android.synthetic.main.activity_list_filter.pull_to_refresh
import kotlinx.android.synthetic.main.activity_list_filter.rv_list
import kotlinx.android.synthetic.main.activity_list_star.*
import org.litepal.LitePal


/**
 * @author 依风听雨
 * @version 创建时间：2018/12/26 08:56
 */
class DataPanelActivity : BaseActivity() {
    val itemsDiscout = arrayOf("全部", "5.5折", "6.5折", "8折", "9折", "9.8折", "10折")
    var mDatas: MutableList<AVObject?> = ArrayList()
    var index = 0
    var queryProperty = ""
    var queryDiscount = ""
    private var isStar = false
    private lateinit var mAdapter: QuickAdapter
    override fun getContentViewId() = R.layout.activity_list_filter
    private lateinit var propertyList: Array<String>

    override fun handlerActivity() {
        mAdapter = QuickAdapter(R.layout.item_text_data2, mDatas)
        rv_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
        rv_list.adapter = mAdapter
//        showProgressDialog()
        ivStar.visibility = View.VISIBLE
        propertyList = resources.getStringArray(R.array.propertyList)
        queryDatas()

        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list)

        pull_to_refresh.setOnRefreshListener(object : OnRefreshListener {
            override fun onRefresh() {
                index = 0
                queryDatas(index)
            }
        })

        mBtnSearch.setOnClickListener {
            val query = mSearchView.text.toString()
            queryDatas(query = query)
        }
        mSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = mSearchView.text.toString()
                queryDatas(query = query)
                return@OnEditorActionListener true
            }
            false
        })

        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this@DataPanelActivity, PanelDetailActivity::class.java)
            intent.putExtra("objId", mDatas[position]?.objectId)
            startActivity(intent)
        }

        spProperty.setItems(propertyList.toList())
        spDiscount.setItems(itemsDiscout.toList())

        spProperty.setOnItemSelectedListener { _, position, _, _ ->
            queryProperty = when (position) {
                1 -> "普"
                2 -> "格"
                3 -> "飞"
                5 -> "地"
                6 -> "岩"
                8 -> "鬼"
                14 -> "超"
                18 -> "妖"
                0 -> ""
                else -> propertyList[position]
            }
            index = 0
            queryDatas(index)
        }
        spDiscount.setOnItemSelectedListener { _, position, _, _ ->
            index = 0
            queryDiscount = if (position == 0) "" else itemsDiscout[position].removeSuffix("折")
            queryDatas(index)
        }

        ivStar.setOnClickListener {
            isStar = !isStar
            ivStar.setImageResource(if (isStar) R.drawable.ic_star_black_24dp else R.drawable.ic_star_border_black_24dp)
            index = 0
            queryDatas(index)
        }

        showTipMessage()
    }


    /**
     * 查询数据
     */
    fun queryDatas(index: Int = 0, pageSize: Int = 20, query: String = "") {
        var where = ""
        if (!TextUtils.isEmpty(query)) {
            where = "pokemonName like '%$query%'"
        }
        //属性筛选
        if (queryProperty.isNotEmpty()) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where += "property like '%$queryProperty%'"
        }

        if (queryDiscount.isNotEmpty()) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where += "discount = '$queryDiscount'"
        }
        if (isStar) {
            if (where.isNotEmpty()) {
                where += " and "
            }
            where += "isStar = 1"
        }
        val dataList =
            LitePal
                .select("pokemonName", "objectId", "discount", "property", "isLevel", "img")
                .limit(pageSize)
                .offset(index * pageSize)
                .order("createdAt desc")
                .where(where)
                .find(DbPokemon::class.java)
        if (index == 0) {
            mDatas.clear()
            pull_to_refresh.finishRefresh()
        }

        for (obj in dataList) {
            val o = AVObject()
            o.put("pokemonName", obj.pokemonName)
            o.put("discount", obj.discount)
            o.put("property", obj.property)
            o.put("isLevel", obj.isLevel)
            o.put("icon", obj.img)
            o.objectId = obj.objectId
            mDatas.add(o)
        }

        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()

    }


    internal inner class QuickAdapter(layoutResId: Int, data: List<AVObject?>) :
        BaseQuickAdapter<AVObject, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: AVObject?) {
            item?.let {
                var property = it.getString("property")
                if (property.length == 18) {
                    property = "全属性"
                }
                val level = if (it.getBoolean("isLevel")) "" else "-89"
                helper.setText(R.id.text, "${it.getString("pokemonName")}($property)$level")
                var discount = it.getDouble("discount")
                if (discount == 0.0) {
                    discount = 10.0
                }
                helper.setText(R.id.tvDiscount, "${discount.subZeroAndDot()}折")
                Glide.with(this@DataPanelActivity)
                    .load(item.getString("icon").replace("large", "thumbnail"))
                    .placeholder(R.drawable.p_def)
                    .error(R.drawable.p_def)
                    .into(helper.getView(R.id.icon))
            }

        }
    }

    override fun getToolbarTitle() = "数据面板"

    private fun showTipMessage() {
        if (TextUtils.isEmpty(sp.getString("guildAttackValue", ""))
            || TextUtils.isEmpty(sp.getString("guildDefenseValue", ""))
        )
            QMUIDialog.MessageDialogBuilder(this)
                .setTitle("提示")
                .setMessage("当前未设置公会加成(右上角按钮进入设置)")
                .addAction(
                    "去设置"
                ) { dialog, _ ->
                    startActivity(Intent(this, GuildSettingActivity::class.java))
                    dialog.dismiss()
                }
                .show()
    }

    override
    fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.panel, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        return when {
            item?.itemId == R.id.action_setting -> {
                startActivity(Intent(this, GuildSettingActivity::class.java))
                true
            }
            item?.itemId == R.id.action_comparison -> {
                startActivity(Intent(this, PanelComparisonActivity::class.java))
                true
            }
            item?.itemId == R.id.action_zygarde -> {
                startActivity(Intent(this, ZygardeActivity::class.java))
                true
            }
            item?.itemId == R.id.action_customize -> {
                startActivity(Intent(this, CustomizeActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}